<template>
    <div>
      <el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
            <!-- 搜索框-->
        <!-- <el-form-item label="单位" prop="oneInstitutional">
           <el-select v-model="searchForm.oneInstitutional" placeholder="请填写单位" style="width:100%;" >
             <el-option v-for="item in oneInstitutionalArr" :label="item.organization" :value="item.organization" :key="item.id"></el-option>
           </el-select>
         </el-form-item> -->
         <el-form-item label="单位类别" prop="organizationLevel">
            <el-select v-model="searchForm.organizationLevel" filterable multiple placeholder="请填写单位类别" style="width:100%;" >
              <el-option v-for="item in unitArr" :label="item" :value="item" :key="item.id"></el-option>
            </el-select>
         </el-form-item>
         <el-form-item label="票类别" prop="ticket">
              <el-select v-model="searchForm.ticket" filterable multiple placeholder="请填写票类别" style="width:100%;" >
                <el-option v-for="item in ticketes" :label="item" :value="item" :key="item"></el-option>
              </el-select>
         </el-form-item>
         <!-- <el-form-item label="备注信息" prop="remarks">
                <el-input size="small" v-model="searchForm.remarks" placeholder="备注信息" clearable></el-input>
         </el-form-item> -->
         <el-form-item label="年" prop="createdate">
           <el-input-number v-model="createdate" controls-position="right" :min="2021" :max="9999"></el-input-number>
         </el-form-item>
         <el-form-item label="投票次数" prop="ticketCount">
           <el-input-number v-model="ticketCount" controls-position="right" :min="1" :max="9999"></el-input-number>
         </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="refreshList()" size="small">查询</el-button>
            <el-button @click="resetSearch()" size="small">重置</el-button>
          </el-form-item>
      </el-form>
        <!-- 导入导出-->
      <el-dialog  title="导入Excel" :visible.sync="isImportCollapse">
          <el-form size="small" :inline="true" v-show="isImportCollapse"  ref="importForm">
             <el-form-item>
              <el-button type="default" @click="downloadTpl()" size="small">下载模板</el-button>
             </el-form-item>
             <el-form-item prop="loginName">
                <el-upload
                  class="upload-demo"
                  :action="`${this.$http.BASE_URL}/peopleinformation/peopleassesteam/peopleAssessTeam/import`"
                  :on-success="uploadSuccess"
                   :show-file-list="true">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只允许导入“xls”或“xlsx”格式文件！</div>
                </el-upload>
            </el-form-item>
          </el-form>
      </el-dialog>
      <div class="bg-white top">
      <el-row>
        <!-- <el-select size="small" v-model="ticket" placeholder="请填写票类别" >
          <el-option v-for="item in tickets" :label="item" :value="item" :key="item"></el-option>
        </el-select>
        <el-button type="warning" size="small" icon="el-icon-edit-outline" @click="createAccounts()" plain>生成票模板</el-button> -->
        <!-- <el-button v-if="hasPermission('peopleinformation:peopleassesteam:peopleAssessTeam:add')" type="primary" size="small" icon="el-icon-plus" @click="add()">新建</el-button> -->
        <!-- <el-button v-if="hasPermission('peopleinformation:peopleassesteam:peopleAssessTeam:edit')" type="warning" size="small" icon="el-icon-edit-outline" @click="edit()"
         :disabled="dataListSelections.length != 1" plain>修改</el-button> -->
         <el-button type="warning" size="small" icon="el-icon-edit-outline" @click="oneKeyImport('now')" plain>本次一键导入</el-button>
         <el-button type="warning" size="small" icon="el-icon-edit-outline" @click="oneKeyImport('add')" plain>新增一键导入</el-button>
        <el-button v-if="hasPermission('peopleinformation:peopleassesteam:peopleAssessTeam:del')" type="danger"   size="small" icon="el-icon-delete" @click="del()"
                  :disabled="dataListSelections.length <= 0" plain>删除
        </el-button>
        <el-button-group class="pull-right">
            <el-button v-if="hasPermission('peopleinformation:peopleassesteam:peopleAssessTeam:import')" type="default" size="small" icon="el-icon-upload2" title="导入" @click="isImportCollapse = !isImportCollapse"></el-button>
            <el-button v-if="hasPermission('peopleinformation:peopleassesteam:peopleAssessTeam:export')" type="default" size="small" icon="el-icon-download" title="导出" @click="exportExcel()"></el-button>
            <el-button
              type="default"
              size="small"
              icon="el-icon-refresh"
              @click="refreshList">
            </el-button>
        </el-button-group>
      </el-row>
    <el-table
      :data="dataList"
       size="small"
      @selection-change="selectionChangeHandle"
      @sort-change="sortChangeHandle"
      v-loading="loading"
      class="table">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
      label="序号"
      type="index">
      </el-table-column>
    <el-table-column
        prop="oneInstitutional"
        show-overflow-tooltip
        label="单位">
      </el-table-column>
    <el-table-column
        prop="organizationLevel"
        show-overflow-tooltip
        label="单位类别">
      </el-table-column>
    <el-table-column
        prop="ticket"
        show-overflow-tooltip
        label="票类别">
      </el-table-column>
    <!-- <el-table-column
        prop="remarks"
        show-overflow-tooltip
        sortable="custom"
        label="备注信息">
      </el-table-column> -->
      <el-table-column
        header-align="center"
        align="center"
        fixed="right"
        :key="Math.random()"
        width="200"
        label="操作">
        <template  slot-scope="scope">
          <!-- <el-button v-if="hasPermission('peopleinformation:peopleassesteam:peopleAssessTeam:view')" type="text" icon="el-icon-view" size="small" @click="view(scope.row.id)">查看</el-button> -->
          <el-button v-if="hasPermission('peopleinformation:peopleassesteam:peopleAssessTeam:edit')" type="text" icon="el-icon-edit" size="small" @click="edit(scope.row.id)">修改</el-button>
          <el-button v-if="hasPermission('peopleinformation:peopleassesteam:peopleAssessTeam:del')" type="text"  icon="el-icon-delete" size="small" @click="del(scope.row.remarks)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageNo"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      background
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    </div>
    <asyn-for-tool ref='asynForTool' @returnData='returnData(arguments)'></asyn-for-tool>
        <!-- 弹窗, 新增 / 修改 -->
    <PeopleAssessTeamForm  ref="peopleAssessTeamForm" @refreshDataList="refreshList"></PeopleAssessTeamForm>
  </div>
</template>

<script>
  import PeopleAssessTeamForm from './PeopleAssessTeamForm'
  export default {
    data () {
      return {
        searchForm: {
          oneInstitutional: '',
          organizationLevel: '',
          ticket: '',
          remarks: '',
          ticketCount: ''
        },
        createdate: new Date().getFullYear(),
        ticketCount: 1,
        finishNumber: 0,
        submitNumber: 0,
        loadings: '',
        unitArr: ['教学', '教辅'],
        dataList: [],
        tickets: [
        '领导班子(校领导票)',
        '领导班子(同级票)',
        '领导班子(教辅群众票)',
        '领导班子(教学群众票)',
        '领导班子(教辅服务对象票)'
        ],
        ticketes: [
          '领导班子(校领导票)',
          '领导班子(同级票)',
          '领导班子(教辅群众票)',
          '领导班子(教学群众票)',
          '领导班子(教辅服务对象票)'
        ],
        time: '',
        timeState: '',
        createDataFilter: [],
        searchList: [],
        state: false,
        ticket: '',
        ticketsData: [],
        createData: [], // 一键导入生成数据
        createDataList: [],
        oneInstitutionalArr: [],
        pageNo: 1,
        pageSize: 10,
        total: 0,
        orderBy: '',
        dataListSelectionDealAgain: [],
        dataListSelections: [],
        isImportCollapse: false,
        loading: false
      }
    },
    components: {
      PeopleAssessTeamForm
    },
    activated () {
      this.refreshList()
    },
    watch: {
      createdate (newVal, oldVal) {
        if (this.createdate === '' || this.createdate === null || this.createdate === undefined || this.ticketCount === undefined || this.ticketCount === undefined || this.ticketCount === undefined) {
          this.searchForm.ticketCount = new Date().getFullYear() + '-' + 1
        } else {
          this.searchForm.ticketCount = this.createdate + '-' + this.ticketCount
        }
      },
      ticketCount (newVal, oldVal) {
        if (this.createdate === '' || this.createdate === null || this.createdate === undefined || this.ticketCount === undefined || this.ticketCount === undefined || this.ticketCount === undefined) {
          this.searchForm.ticketCount = new Date().getFullYear() + '-' + 1
        } else {
          this.searchForm.ticketCount = this.createdate + '-' + this.ticketCount
        }
      }
    },
    methods: {
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.searchForm.ticketCount = ''
        if (this.createdate === '' || this.createdate === null || this.createdate === undefined || this.ticketCount === undefined || this.ticketCount === undefined || this.ticketCount === undefined) {
          this.searchForm.ticketCount = new Date().getFullYear() + '-' + 1
        } else {
          this.searchForm.ticketCount = this.createdate + '-' + this.ticketCount
        }
        if (this.searchForm.organizationLevel !== '') {
          this.searchForm.organizationLevel = this.searchForm.organizationLevel.join(',')
        }
        if (this.searchForm.ticket !== '') {
          this.searchForm.ticket = this.searchForm.ticket.join(',')
        }
        this.$http({
          url: '/peopleinformation/peopleassesteam/peopleAssessTeam/list',
          method: 'get',
          params: {
            'pageNo': this.pageNo,
            'pageSize': this.pageSize,
            'orderBy': this.orderBy,
            ...this.searchForm
          }
        }).then(({data}) => {
          if (data && data.success) {
            if (this.searchForm.organizationLevel !== '') {
              this.searchForm.organizationLevel = this.searchForm.organizationLevel.split(',')
            }
            if (this.searchForm.ticket !== '') {
              this.searchForm.ticket = this.searchForm.ticket.split(',')
            }
            this.dataList = data.page.list
            this.total = data.page.count
            this.loading = false
            this.searchOneInstitutional()
          }
        })
      },
      // 搜索框下拉数据提供 单位名称下拉框数据请求
      searchOneInstitutional () {
        this.$http({
          url: '/peopleinformation/organization/nameOfOrganization/treeData',
          method: 'get'
        }).then(({data}) => {
          this.oneInstitutionalArr = []
          for (let index = 0; index < data.treeData.length; index++) {
            this.oneInstitutionalArr.push(data.treeData[index])
          }
        })
      },
      importAssess () {
        this.$confirm('正在为您统计是否有重复数据,请等待几秒钟后点击确认否则会出现统计错误的情况!', '提示', {
            confirmButtonText: '确定',
            showClose: false
          }).then(() => {
          this.$confirm(`您导入数据数量为${this.dataListSelections.length}实际可导入数据数量为${this.dataListSelectionDealAgain.length}点击确认后开始导入如有问题请核对是否重复或者等待时间过短点击取消即可!`, '统计完成', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              showClose: false,
              type: 'warning'
            }).then(() => {
              this.state = true
              this.loadings = this.$loading({
                lock: true,
                text: '保存中，请勿刷新网页',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              })
              this.$refs.asynForTool.func('/peopleinformation/peopleassesteam/peopleAssessTeam/save', 'post', this.dataListSelections, true)
              // 调用异步循环组件的循环请求方法
              if (this.ticket === '领导班子(校领导票)') {
                this.$refs.asynForTool.func('/ticket/schlealeadership/schoolleaderLeadership/save', 'post', this.dataListSelectionDealAgain)
              } else if (this.ticket === '领导班子(同级票)') {
                this.$refs.asynForTool.func('/ticket/samelevelleadership/samelevelLeadership/save', 'post', this.dataListSelectionDealAgain)
              } else if (this.ticket === '领导班子(教学群众票)') {
                this.$refs.asynForTool.func('/ticket/crowdleadershipteach/crowdLeadershipTeach/save', 'post', this.dataListSelectionDealAgain)
              } else if (this.ticket === '领导班子(教辅群众票)') {
                this.$refs.asynForTool.func('/ticket/crowdleadershipfu/crowdLeadershipFu/save', 'post', this.dataListSelectionDealAgain)
              } else if (this.ticket === '领导班子(教辅服务对象票)') {
                this.$refs.asynForTool.func('/ticket/servicefu/serviceFu/save', 'post', this.dataListSelectionDealAgain)
              }
              this.$message({
                type: 'success',
                message: '导入成功!'
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '导入取消'
              })
            })
          })
      },
      returnData (value) {
        this.finishNumber++
        if (this.state === 'save') {
         if (this.finishNumber === this.submitNumber) {
           this.bindDataRepeat(this.createDataFilter)
         }
        } else if (this.state === 'list') {
          if (value[0].page.list.length === 0) {
            this.createDataFilter.push(this.createData[value[2]])
          }
          if (this.finishNumber === this.submitNumber) {
            this.finishNumber = 0
            this.submitNumber = this.createDataFilter.length
            this.state = 'save'
            if (this.createDataFilter.length !== 0) {
              this.$refs.asynForTool.func('/peopleinformation/peopleassesteam/peopleAssessTeam/save', 'post', this.createDataFilter, true)
            } else {
              this.refreshList()
              this.loadings.close()
            }
          }
        }
      },
      // 绑定数据查重
      async bindDataRepeat (data) {
        var xiaolingdaoArr = []
        var tongjiArr = []
        var jiaoxuequnzhongArr = []
        var jiaofuqunzhong = []
        var jiguanzhongcengArr = []
        var jiaofufuwuArr = []
        if (data !== undefined && data.length !== 0) {
          for (let i in data) {
            var datas = data[i].ticket.split(',')
            var dataFilter = this.lodash.pick(data[i], 'mark', 'organizationLevel')
            this.$set(dataFilter, 'unit', data[i].oneInstitutional)
            this.$set(dataFilter, 'ticketCount', this.time)
            for (let j in datas) {
              if (datas[j] === '领导班子(校领导票)') {
                xiaolingdaoArr.push(dataFilter)
              } else if (datas[j] === '领导班子(同级票)') {
                tongjiArr.push(dataFilter)
              } else if (datas[j] === '领导班子(教学群众票)') {
                jiaoxuequnzhongArr.push(dataFilter)
              } else if (datas[j] === '领导班子(教辅群众票)') {
                jiaofuqunzhong.push(dataFilter)
              } else if (datas[j] === '机关中层干部(服务对象票)') {
                jiguanzhongcengArr.push(dataFilter)
              } else if (datas[j] === '领导班子(教辅服务对象票)') {
                jiaofufuwuArr.push(dataFilter)
              }
            }
            if (Number(i) === data.length - 1) {
              if (this.timeState === 'add') {
                this.$http({
                  url: `/peopleinformation/checktime/checkTime/save`,
                  method: 'post',
                  data: {
                    time: this.time,
                    remarks: '单位'
                  }
                })
              }
              this.$refs.asynForTool.func('/ticket/schlealeadership/schoolleaderLeadership/save', 'post', xiaolingdaoArr)
              this.$refs.asynForTool.func('/ticket/samelevelleadership/samelevelLeadership/save', 'post', tongjiArr)
              this.$refs.asynForTool.func('/ticket/crowdleadershipteach/crowdLeadershipTeach/save', 'post', jiaoxuequnzhongArr)
              this.$refs.asynForTool.func('/ticket/crowdleadershipfu/crowdLeadershipFu/save', 'post', jiaofuqunzhong)
              this.$refs.asynForTool.func('/ticket/serviceorgan/serviceOrgan/save', 'post', jiguanzhongcengArr)
              this.$refs.asynForTool.func('/ticket/servicefu/serviceFu/save', 'post', jiaofufuwuArr)
              this.loadings.close()
              this.refreshList()
            }
          }
        } else {
          this.loadings.close()
          this.refreshList()
        }
      },
      fnc (httpStr, httpData) {
        this.$http({
             url: httpStr + 'list',
             method: 'get',
             params: {
               'pageSize': 9999,
               'mark': httpData.mark
             }
         }).then(({data}) => {
          if (data && data.success) {
            if (data.page.list.length === 0) {
              this.$http({
                  url: httpStr + 'save',
                  method: 'post',
                  data: httpData
              })
            }
          }
        })
      },
      // 一键导入弹窗
      importAlert (state) {
        if (this.oneInstitutionalArr.length === 0) {
          this.$confirm(`当前单位未加载完全,请稍后几秒再试`, '提示', {
              confirmButtonText: '确定',
              showClose: false
            })
        } else {
          this.importLoading('导入中，请勿刷新网页')
        }
      },
      // 加载样式
      importLoading (content) {
        this.loadings = this.$loading({
          lock: true,
          text: content,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      },
      // 一键导入
      oneKeyImport (val) {
        this.importAlert()
        this.createData = []
        this.createDataList = []
        this.createDataFilter = []
        this.refuseCheck(val)
      },
      // 重复检测
      refuseCheck (val) {
        this.time = ''
        this.timeState = ''
        this.$http({
          url: '/peopleinformation/checktime/checkTime/list',
          method: 'get',
          params: {
            'pageSize': 9999,
            'remarks': '单位'
          }
        }).then(({data}) => {
          if (data && data.success) {
            if (data.page.list[0] !== undefined) {
              if (val === 'add') {
                this.time = data.page.list[0].time.split('-')[0] + '-' + (Number(data.page.list[0].time.split('-')[1]) + 1)
                this.timeState = 'add'
              } else {
                this.time = data.page.list[0].time
                this.timeState = ''
              }
            } else {
              this.time = new Date().getFullYear() + '-' + 1
              this.timeState = 'add'
            }
            for (let index in this.oneInstitutionalArr) {
              if (this.oneInstitutionalArr[index].organizationLevel !== '机关') {
                this.createData.push({
                  mark: this.oneInstitutionalArr[index].id,
                  remarks: this.oneInstitutionalArr[index].id,
                  oneInstitutional: this.oneInstitutionalArr[index].organization,
                  organizationLevel: this.oneInstitutionalArr[index].organizationLevel,
                  ticket: this.oneInstitutionalArr[index].organizationLevel === '教学' ? '领导班子(校领导票),领导班子(同级票),领导班子(教学群众票)' : '领导班子(校领导票),领导班子(同级票),领导班子(教辅群众票),领导班子(教辅服务对象票)',
                  ticketCount: this.time
                })
                this.createDataList.push({
                  oneInstitutional: this.oneInstitutionalArr[index].organization,
                  ticketCount: this.time
                })
              }
              if (this.oneInstitutionalArr.length - 1 === index - 0) {
                this.finishNumber = 0
                this.submitNumber = this.createData.length
                this.state = 'list'
                this.$refs.asynForTool.func('/peopleinformation/peopleassesteam/peopleAssessTeam/list', 'get', this.createDataList, true)
              }
            }
           }
          })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageNo = 1
        this.refreshList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageNo = val
        this.refreshList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },

    // 排序
      sortChangeHandle (obj) {
        if (obj.order === 'ascending') {
          this.orderBy = obj.prop + ' asc'
        } else if (obj.order === 'descending') {
          this.orderBy = obj.prop + ' desc'
        } else {
          this.orderBy = ''
        }
        this.refreshList()
      },
      // 新增
      add () {
        this.$refs.peopleAssessTeamForm.init('add', '')
      },
      // 修改
      edit (id) {
        id = id || this.dataListSelections.map(item => {
          return item.id
        })[0]
        this.$refs.peopleAssessTeamForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.peopleAssessTeamForm.init('view', id)
      },
      // 删除
      del (remarks) {
        let ids = remarks || this.dataListSelections.map(item => {
          return item.remarks
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.$http({
            url: '/peopleinformation/peopleassesteam/peopleAssessTeam/delete',
            method: 'delete',
            params: {
              'ids': ids,
              'ticketCount': this.searchForm.ticketCount
              }
          }).then(({data}) => {
            if (data && data.success) {
              this.$http({
                url: '/peopleinformation/peopleassesteam/peopleAssessTeam/deleteSchoolleaderLeadership',
                method: 'delete',
                params: {
                  'ids': ids,
                  'ticketCount': this.searchForm.ticketCount
                }
              }).then(({data}) => {
                if (data && data.success) {
                  this.$http({
                    url: '/peopleinformation/peopleassesteam/peopleAssessTeam/deleteSamelevelLeadership',
                    method: 'delete',
                    params: {
                      'ids': ids,
                      'ticketCount': this.searchForm.ticketCount
                      }
                  }).then(({data}) => {
                    if (data && data.success) {
                      this.$http({
                        url: '/peopleinformation/peopleassesteam/peopleAssessTeam/deleteCrowdLeadershipTeach',
                        method: 'delete',
                        params: {
                          'ids': ids,
                          'ticketCount': this.searchForm.ticketCount
                          }
                      }).then(({data}) => {
                        if (data && data.success) {
                          this.$http({
                            url: '/peopleinformation/peopleassesteam/peopleAssessTeam/deleteCrowdLeadershipFu',
                            method: 'delete',
                            params: {
                              'ids': ids,
                              'ticketCount': this.searchForm.ticketCount
                              }
                          }).then(({data}) => {
                            if (data && data.success) {
                              this.$http({
                                url: '/peopleinformation/peopleassesteam/peopleAssessTeam/deleteServiceFu',
                                method: 'delete',
                                params: {
                                  'ids': ids,
                                  'ticketCount': this.searchForm.ticketCount
                                  }
                              }).then(({data}) => {
                                if (data && data.success) {
                                  this.$http({
                                    url: '/peopleinformation/peopleassesteam/peopleAssessTeam/list',
                                    method: 'get',
                                    params: {
                                      'pageSize': 9999,
                                      'ticketCount': this.searchForm.ticketCount
                                    }
                                  }).then(({data}) => {
                                    if (data.page.list.length === 0) {
                                      this.$http({
                                        url: '/peopleinformation/checktime/checkTime/deleteCheck',
                                        method: 'delete',
                                        params: {
                                          'ids': this.searchForm.ticketCount
                                        }
                                      })
                                    }
                                    this.refreshList()
                                    this.loading = false
                                  })
                                }
                               })
                            }
                            })
                        }
                        })
                    }
                    })
                }
              })
            }
          })
        })
      },
      // 导入成功
      uploadSuccess (res, file) {
        if (res.success) {
          this.$message.success({dangerouslyUseHTMLString: true,
            message: res.msg})
        } else {
          this.$message.error(res.msg)
        }
      },
      // 下载模板
      downloadTpl () {
        this.$utils.download('/peopleinformation/peopleassesteam/peopleAssessTeam/import/template')
      },
      exportExcel () {
        let params = {
          ...this.searchForm
        }
        this.$utils.download('/peopleinformation/peopleassesteam/peopleAssessTeam/export', params)
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      }
    }
  }
</script>
